<?php
//异步javascript和xml
/* 
 * $ajax = new lib_ajax();
 * $ajax->show('content here');
 * $ajax->success()->json(array('content'=>'ok'));
 * $ajax->fail();
 * */
class lib_ajax{
	private $success = true;
	
	private $fail_error = '';
	
	private $auto_render = false;
	
	private $to_json = false;
	
	private $params = array();
	
	private $content = '';
	
	public function success($content = 'action success') {
        $this->success = true;
        $this->content = $content;
        return $this;
    }
	public function fail($error = 'unkown reason') {
        $this->success = false;
        $this->fail_error = $error;
        return $this;
    }
    
    public function show($content = 'There is no content'){
    	$this->auto_render = true;
    	$this->to_json = false;
    	$this->content = (string)$content;
    	return $this;
    }
    
    public function json($params = array()){
    	$this->to_json = true;
    	$this->auto_render = false;
    	if (!is_array($params)){
    		$this->fail('参数非数组');
    	}else{
    		$this->params = $params;
    	}
    	return $this;
    }
    
    public function set_param($key,$value){
    	$this->params[$key] = $value;
    	return $this;
    }
    
    public function exec(){
    	if (true === $this->auto_render){
    		echo $this->content;
    		return $this;
    	}
    	if (true === $this->to_json){
    		$status = array(true=>'success',false=>'failed');
    		$this->params['status'] = $status[$this->success];
    		$this->params['content'] = $this->content;
    		$this->params['error'] = $this->fail_error;
    		echo json_encode($this->params);
    		return $this;
    	}
    	var_export($this->params);
    	return false;
    }
}